import {  View, Input } from '@tarojs/components'
import { useEffect, useReducer, useState } from 'react'
import $style from './index.module.scss'
import { reducer } from '../../../utils'

export default (props:{options:number[], price:number, onChange:{(value:string|number) : void}}) => {
    let [optionList, setoptionList] = useState<any[]>([])
    const [formData, formDataDispatch] = useReducer(reducer, {
        selectedOptionIndex : -1,
        customQuantity : '',
    })
    function selectOption(params:any) {
        formDataDispatch(params)
        props.onChange(params.chargeQuantity)
    }
    function inputQuantity(quantity:number|string) {
        selectOption({chargeQuantity : quantity, customQuantity : quantity, selectedOptionIndex : -1})
    }

    let options = props.options

    useEffect(() => {
        if(options) {
            setoptionList(typeof options == 'string' ? JSON.parse(options) : props.options)
        }else {
            let price = props.price || 0
            if(price > 0) {
                setoptionList([price, price * 2, , price * 3, , price * 4])
            }
        }
    }, [options])

    return <View className={$style.chargeOptions}>
        {
            optionList.map((option, index) => {
                let optionClass = $style.option

                if(formData.selectedOptionIndex == index) {
                    optionClass += (' ' + $style.selected)
                }

                return  <View className={optionClass} onClick={() => { selectOption({chargeQuantity : option, selectedOptionIndex : index, customQuantity : ''}) }}>
                    <View className={$style.wrap + ' xy'}>{option}元</View>
                </View>
            })
        }
        
        <View className={$style.option}>
            <View className={$style.wrap + ' w-100 h-100'}>
                <Input type='digit' placeholderClass='color-999 f-24' placeholder='自定义' className='w-100 h-100' value={formData.customQuantity} onInput={e => inputQuantity(e.detail.value) } />
            </View>
        </View>
    </View>
}